<?php

/**
 *  商品表
 */

namespace app\api\model;

use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Lang;

class Product extends BaseModel
{
    protected $append = ['unit'];
    protected $attributes = [
        'computing_unit' => [
            1 => 'h/s',
            2 => 'Kh/s',
            3 => 'Mh/s',
            4 => 'Gh/s',
            5 => 'Th/s',
            6 => 'Ph/s',
            7 => 'Eh/s'
        ],
        'powerline_standards' => [
            1 => 'CN - Power Cord',
            2 => 'USA - Power Cord',
            3 => 'EURO - Power Cord',
            4 => 'UK - Power Cord',
            5 => 'Other'
        ]
    ];

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-17 15:13:23 
     * @param [type] @required
     * @return Renderable
     */
    public function getAttributes($attributes)
    {
        return $this->attributes[$attributes];
    }

    /**
     *  管理库存表
     */

    public function getUnitAttr($value, $data)
    {
        if (!isset($data['computing_unit'])) {
            return '';
        }
        $statusList = $this->attributes;
        if (isset($statusList['computing_unit'][$data['computing_unit']])) {
            return $statusList['computing_unit'][$data['computing_unit']];
        } else {
            return '';
        }
    }


    /**
     *  功率
     */
    public function getPowerAttr($value, $data)
    {
        if (empty($value)) {
            return '';
        } else {
            return $value . 'w';
        }
    }

    /**
     *  管理库存表
     */
    public function inventory()
    {
        return $this->hasMany('Inventory', 'productid', 'id');
    }

    /**
     *  关联品牌
     */
    public function brand()
    {
        return $this->hasOne('ProductBrand', 'id', 'brand');
    }

    /**
     *  关联分类
     */
    public function category()
    {
        return $this->hasOne('ProductCategory', 'id', 'category');
    }

    /**
     *  关联货币算法
     */
    public function currency()
    {
        return $this->belongsToMany('ProductCurrency', 'ProductCurrencyLink', 'productid', 'currencyid', '', '');
    }

    /**
     *  关联图片
     */
    public function mainPhoto()
    {
        return $this->hasOne(Images::class, 'id', 'main_photo');
    }
    public function getCacheKey($key,$scene)
    {
        return 'product_profit_'.$scene.'_'.$key;
    }
    /**
     * 计算收益需要的商品信息
     */
    public function getProductInfoForProfit($id,$func)
    {
        if(!$id && !$func){
            return [];
        }
        #根据不同场景 获取不同的商品id
        $productId = [$id];

        if($func){
            $productId = $this->$func($id);
        }

        if(!$productId){
            return [];
        }

        $data = self::whereIn('id',$productId)->field('id,hashrate,computing_unit,power,algorithm,cname,brand,release_date,algorithm')->select()->toArray();
        return $data;
    }

    /**
     * 根据品牌id获取商品id
     * @param $id
     */
    public function getProductIdByBrandId($id){
       return $data = self::where([
            'status' =>1,
            'is_del' =>0,
            'type' =>1,
            'brand' =>$id,
        ])->column('id');
    }
    /**
     * 获取推荐商品id
     */
    public function getRecommendList($id) :array
    {
     if(!$id){
         return [];
     }
     #通过 商品id 获取算法  然后通过算法 取同算法的商品id
     $key = $this->getCacheKey($id,'recommend');
     $data = Cache::get($key);
     if(!$data){
        #没有缓存 查数据库
        $algorithm = self::where('id',$id)->column('algorithm');
       if(empty($algorithm) || !isset($algorithm[0]) || empty($algorithm[0])){
           return [];
       }
        $algorithm = explode(',',$algorithm[0]);
        $data = [];
        foreach ($algorithm as $v){
            $productIds = self::whereRaw('FIND_IN_SET(?, algorithm)', [$v])->where('id','<>',$id)->column('id');
            $data = array_merge($data,$productIds);
        }
         Cache::set($key,$data,120);
     }
     return $data;
    }
    /**
     * 获取收益计算的商品id
     */
    public function getProductList($id) :array
    {
        $data = self::name('product_merge')->alias('pm')->leftJoin('product p','p.id = pm.primary_pid')->where(
            [
                'pm.status' =>1,
                'pm.is_del' =>0,
                'p.is_del' =>0,
                'p.status' =>1,
                'p.type' =>1,
            ]
        )->column('p.id');

        return $data;
    }
    public function getMinPrice($productIds){
        if (empty($productIds)) return [];

        // 单次联合查询获取所有结果
        $results = Db::name('inventory')
            ->leftJoin('db_product_price',
                'db_inventory.id = db_product_price.inventory_id 
            AND db_product_price.is_del = 0 
            AND db_product_price.transaction_currency_id = 214'
            )
            ->fieldRaw('db_inventory.productid, MIN(price) as min_price')
            ->whereIn('db_inventory.productid', $productIds)
            ->where('db_inventory.is_sale', 1)
            ->where('db_inventory.is_del', 0)
            ->whereRaw('(db_inventory.available_qty > db_inventory.lock_qty OR db_inventory.allow_zero_stock_sale = 1)')
            ->group('db_inventory.productid')
            ->select();

        // 构建价格映射表
        $priceMap = [];
        foreach ($results as $row) {
            $priceMap[$row['productid']] = (float)$row['min_price'];
        }


        return $priceMap;
    }
}
